package svc

import (
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"im_sys/apps/user/models"
	"im_sys/apps/user/rpc/internal/config"
	"im_sys/pkg/constants"
	"im_sys/pkg/ctxdata"
	"time"
)

type ServiceContext struct {
	Config config.Config

	UserModel models.UsersModel

	*redis.Redis
}

func NewServiceContext(c config.Config) *ServiceContext {
	conn := sqlx.NewMysql(c.Mysql.DataSource)
	return &ServiceContext{
		Config: c,

		UserModel: models.NewUsersModel(conn, c.Cache),

		Redis: redis.MustNewRedis(c.Redisx),
	}
}

func (ctx *ServiceContext) SetRootToken() error {
	// 生成jwt token
	token, err := ctxdata.GetJwtToken(ctx.Config.Jwt.AccessKey, time.Now().Unix(), ctx.Config.Jwt.AccessExpire, constants.SystemRootUid)
	if err != nil {
		return err
	}
	// 写入到日志中
	return ctx.Redis.Set(constants.RedisSystemRootToken, token)
}
